//
//  SCGIFViewController.m
//  BanBu
//
//  Created by Jc Zhang on 13-1-5.
//
//

#import "SCGIFViewController.h"
#import "SCGIFImageView.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_HelpViewController.h"
#import "BanBu_AppDelegate.h"
#import "MRZoomScrollView.h"
#import "SDImageCache.h"
#import "WXOpen.h"
#import "TKLoadingView.h"
#import "ShareViewController.h"
#import "BanBu_NavButton.h"
#import "BanBu_ChatViewController.h"
#import "UIViewController+Animation.h"

@interface SCGIFViewController ()

@end

@implementation SCGIFViewController
@synthesize isBreaker;
int currentPage = -1;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)pop
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    if(!isBreaker)
    {
        self.view.backgroundColor = [UIColor blackColor];
        UIBarButtonItem *backButton = [[[UIBarButtonItem alloc]initWithTitle:NSLocalizedString(@"returnButton", nil) style:UIBarButtonItemStylePlain target:self action:@selector(backAction)]autorelease];
        self.navigationItem.leftBarButtonItem = backButton;
        
        UIBarButtonItem *sendButton = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"sendReply", nil) style:UIBarButtonItemStylePlain target:self action:@selector(sendButtonPressed:)] autorelease];
        
        self.navigationItem.rightBarButtonItem = sendButton;
        
        NSString* filePath = [AppComManager pathForMsgMedia:self.gifString];
        SCGIFImageView* gifImageView = [[[SCGIFImageView alloc] initWithGIFFile:filePath] autorelease];
        
        gifImageView.frame = CGRectMake(0, 0, gifImageView.image.size.width, gifImageView.image.size.height);
        gifImageView.center = self.view.center;
        [self.view addSubview:gifImageView];
    }
    else
    {
        self.view.multipleTouchEnabled = YES;
        //
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(refreshUI)
                                                     name: @"refreshUIImage"
                                                   object: nil];
        // Do any additional setup after loading the view.
        self.title = NSLocalizedString(@"scanPic", nil);
        self.view.backgroundColor = [UIColor whiteColor];
        
        BanBu_NavButton *btn_return = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeBack];
        btn_return.position = ButtonPositionLeft;
//        btn_return.frame=CGRectMake(0, 0,50, 30);
        [btn_return addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
//        btn_return.titleLabel.font = [UIFont systemFontOfSize:14];
        UIBarButtonItem *cancelItem = [[[UIBarButtonItem alloc] initWithCustomView:btn_return] autorelease];
        self.navigationItem.leftBarButtonItem = cancelItem;
        [btn_return release];
        
        BanBu_NavButton *listButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
        listButton.position = ButtonPositionRight;
        listButton.frame = CGRectMake(0, 0, 50, 30);
        listButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [listButton setTitle:NSLocalizedString(@"sendReply", nil) forState:UIControlStateNormal];
        [listButton addTarget:self action:@selector(sendButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightItem = [[[UIBarButtonItem alloc] initWithCustomView:listButton] autorelease];
        self.navigationItem.rightBarButtonItem = rightItem;
        
        UIScrollView *imageScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height-44)];
        imageScroll.contentSize = CGSizeMake(320*_arrayData.count, __MainScreen_Height-44);
        imageScroll.contentOffset = CGPointMake(320*self.indexPathSelected, 0);
        imageScroll.pagingEnabled = YES;
        imageScroll.tag = 3456;
        imageScroll.backgroundColor = [UIColor clearColor];
        imageScroll.delegate = self;
        imageScroll.showsHorizontalScrollIndicator = NO;
        imageScroll.showsVerticalScrollIndicator = NO;
        imageScroll.decelerationRate = UIScrollViewDecelerationRateFast;

        [self.view addSubview:imageScroll];
        
        currentPage = self.indexPathSelected;
        [imageScroll release];
        
        
        for(int i = 0;i<_arrayData.count;i++)
        {
            MRZoomScrollView *_zoomScrollView= [[MRZoomScrollView alloc]init];
            _zoomScrollView.frame = CGRectMake(i*320, 0, 320, __MainScreen_Height-44);
            _zoomScrollView.showsVerticalScrollIndicator = NO;
            _zoomScrollView.showsHorizontalScrollIndicator = NO;
            _zoomScrollView.multipleTouchEnabled = YES;
            _zoomScrollView.contentSize = CGSizeMake(320, __MainScreen_Height-44-40);
            _zoomScrollView.tag = (i+1)*10;
            _zoomScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
            
            [imageScroll addSubview:_zoomScrollView];
            _zoomScrollView.backgroundColor = [UIColor clearColor];
            [_zoomScrollView release];
            
        }
        NSDictionary *object = [NSDictionary dictionaryWithDictionary:[self.arrayData objectAtIndex:self.indexPathSelected]];
        NSString *url=[object valueForKey:@"saytext"];
        self.hints = [object valueForKey:@"hints"];
        MRZoomScrollView *imageView1 = (MRZoomScrollView *)[imageScroll viewWithTag:(self.indexPathSelected+1)*10];
        imageView1.isReady = NO;
        activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        activity.frame = CGRectMake(160-20, (__MainScreen_Height-44)/2,40, 40);
        activity.center = CGPointMake(160,((float)__MainScreen_Height)/2);//
   
        activity.hidesWhenStopped = YES;
        activity.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin |
        UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin;
        [self.view addSubview:activity];
        [activity release];
        [activity startAnimating];
        if([url hasSuffix:@".gif"])
        {
            imageView1.userInteractionEnabled = NO;
        }
        
        
        [(SCGIFImageView *)imageView1.imageView initWithURL:url];
         
        UIButton *btu2 = [UIButton buttonWithType:UIButtonTypeCustom];
        btu2.tag = 52152;

        btu2.titleLabel.font = [UIFont systemFontOfSize:14.0];
        [btu2 setBackgroundColor:[UIColor clearColor]];

        [btu2 setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        btu2.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        [btu2.layer setBorderColor:[[UIColor grayColor] CGColor]];
        
        [btu2 setFrame:CGRectMake(0,0, 320, 45)];
        [self.view addSubview:btu2];
        UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
        leftButton.frame = CGRectMake(10, (__MainScreen_Height-44)/2-23, 31, 46);
        leftButton.alpha = 0.4;
        if(self.indexPathSelected == 0)
        {
            leftButton.hidden = YES;
        }
        leftButton.tag = 135;
        [leftButton setBackgroundImage:[UIImage imageNamed:@"向左滚动.png"]  forState:UIControlStateNormal];
        [leftButton addTarget:self action:@selector(swapToNextPage:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:leftButton];
        UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        rightButton.frame = CGRectMake(280, (__MainScreen_Height-44)/2-23, 31, 46);
        rightButton.alpha = 0.4;
        rightButton.tag = 246;
        if(self.indexPathSelected == _arrayData.count-1)
        {
            rightButton.hidden = YES;
        }
        [rightButton setBackgroundImage:[UIImage imageNamed:@"向右滚动.png"]  forState:UIControlStateNormal];
        [rightButton addTarget:self action:@selector(swapToNextPage:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:rightButton];
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)backAction{
    
    [self dismissViewControllerAnimated:YES];
}

-(void)sendButtonPressed:(id)sender
{
    if(!activity.isAnimating)
    [self sendMessageTochat];
}


-(void)sendMessageTochat
{
    UIActionSheet *conSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"ice_actionSheetButtionTitle", nil),nil];

    [conSheet showInView:self.view];
    [conSheet release];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    [self dismissViewControllerAnimated:NO];
    
    
    NSDictionary *object = [NSDictionary dictionaryWithDictionary:[self.arrayData objectAtIndex:currentPage]];
    NSString *thumbImageStr = [object valueForKey:@"saytext"];

    NSString *imageString=thumbImageStr;
    NSMutableDictionary *picDictionary=[[[NSMutableDictionary alloc]init] autorelease];
    // 发送图片
    
    [picDictionary setValue:[self getBigPicUrl:imageString] forKey:@"image"];
    NSArray *suffixArr = [[NSArray alloc]initWithArray:[imageString componentsSeparatedByString:@"."]];
    [picDictionary setValue:[suffixArr lastObject] forKey:@"filetype"];
    [picDictionary setValue:[NSNumber numberWithInt:ChatCellTypeImage] forKey:KeyType];
    [picDictionary setValue:@"pb" forKey:KeyShowFrom];
    [suffixArr release];

    if(buttonIndex == 0)
    {
        // 这是url
        
        [[NSNotificationCenter defaultCenter]postNotificationName:kSendMsgAllTypeNotification object:picDictionary];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"popToChat" object:nil];
        
        if (self.immediateExit)
        {
            [self popself];
        }
        
    }

}

-(void)popself
{
    BanBu_ChatViewController *chat = nil;
    for(UIViewController *vc in [self.navigationController viewControllers])
        if([vc isKindOfClass:[BanBu_ChatViewController class]])
        {
            chat = (BanBu_ChatViewController *)vc;
            break;
        }
    if(chat)
    {
        [self.navigationController popToViewController:chat animated:YES];
    }
    else
    {
        BanBu_ChatViewController *chat=[[BanBu_ChatViewController alloc]init];
        
        [self.navigationController pushViewController:chat animated:YES];
        [chat release];
    }
}


-(void)swapToNextPage:(UIButton *)button
{
    UIScrollView *scroll = (UIScrollView *)[self.view viewWithTag:3456];
    if(button.tag==135&&currentPage>0)
    {
            [UIView animateWithDuration:0.3 animations:^{
            scroll.contentOffset = CGPointMake((currentPage-1)*320, 0);
     
            currentPage--;
        } completion:^(BOOL finished) {
        }];
        UIButton *button1 = (UIButton *)[self.view viewWithTag:246];
        button1.hidden = NO;
        if(currentPage == 0)
        {
            button.hidden = YES;
        }
        
    }
    if(button.tag==246&&currentPage<_arrayData.count-1)
    {
            [UIView animateWithDuration:0.3 animations:^{
            scroll.contentOffset = CGPointMake((currentPage+1)*320, 0);
            currentPage++;
        }];
        UIButton *button1 = (UIButton *)[self.view viewWithTag:135];
        button1.hidden = NO;
        if(currentPage == _arrayData.count-1)
        {
            button.hidden = YES;
        }
        
    }
    
    MRZoomScrollView *aview2 = (MRZoomScrollView *)[scroll viewWithTag:(currentPage+1)*10];
    aview2.isLarger = NO;
    [aview2 setZoomScale:0.5];
    
    NSDictionary *object = [NSDictionary dictionaryWithDictionary:[self.arrayData objectAtIndex:currentPage]];
    NSString *url=[object valueForKey:@"saytext"];
    MRZoomScrollView *aview = (MRZoomScrollView *)[scroll viewWithTag:(currentPage+1)*10];
    aview.isLarger = NO;
    [aview setZoomScale:0.5];
    [self refreshUI];

    if([url hasSuffix:@".gif"])
    {        aview.userInteractionEnabled = NO;
    }
    else
    {
        aview.userInteractionEnabled = YES;
    }
    
    
    [(SCGIFImageView *)aview.imageView initWithURL:url];

    NSString *suffix = nil;
    
    NSRange range = [url rangeOfString:@"." options:NSBackwardsSearch];
    
    if(range.location!=NSNotFound)
    {
        suffix = [url substringFromIndex:range.location];
        url = [url stringByAppendingString:suffix];
    }
    NSData *data = [NSData dataWithContentsOfFile:[[SDImageCache sharedImageCache] cachePathForKey:url]];
    
    if(data.length<4)
    {
        [activity startAnimating];
    }
    

}


-(void)dealloc
{
    self.delegate = nil;

    self.arrayData = nil;

    self.hints = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger page = scrollView.contentOffset.x/320;
    if(currentPage != page)
    {
        
        MRZoomScrollView *aview2 = (MRZoomScrollView *)[scrollView viewWithTag:(currentPage+1)*10];
        aview2.isLarger = NO;
        [aview2 setZoomScale:0.5];
        
        currentPage = page;
        NSDictionary *object = [NSDictionary dictionaryWithDictionary:[self.arrayData objectAtIndex:currentPage]];
        NSString *url=[object valueForKey:@"saytext"];
        MRZoomScrollView *aview = (MRZoomScrollView *)[scrollView viewWithTag:(currentPage+1)*10];
        aview.isLarger = NO;
        [aview setZoomScale:0.5];
        [self refreshUI];
        if([url hasSuffix:@".gif"])
        {
            aview.userInteractionEnabled = NO;
        }
        else
        {
            aview.userInteractionEnabled = YES;
        }
        
        
        [(SCGIFImageView *)aview.imageView initWithURL:url];
        
        NSString *suffix = nil;
        
        NSRange range = [url rangeOfString:@"." options:NSBackwardsSearch];
        
        if(range.location!=NSNotFound)
        {
            suffix = [url substringFromIndex:range.location];
            url = [url stringByAppendingString:suffix];
        }
        NSData *data = [NSData dataWithContentsOfFile:[[SDImageCache sharedImageCache] cachePathForKey:url]];
        
        if(data.length<4)
        {
            [activity startAnimating];
        }
        
    }
    UIButton *button1 = (UIButton *)[self.view viewWithTag:135];
    UIButton *button2 = (UIButton *)[self.view viewWithTag:246];
    if(currentPage == 0)
    {
        
        button1.hidden = YES;
    }
    else
        if(currentPage == 19)
        {
            button2.hidden = YES;
        }
        else
        {
            button1.hidden = NO;
            button2.hidden = NO;
        }
    
}

-(void)refreshUI
{
    if(activity.isAnimating)
        [activity stopAnimating];
    
    
    UIScrollView *scrollView = (UIScrollView *)[self.view viewWithTag:3456];
    MRZoomScrollView *gifImageView = (MRZoomScrollView *)[scrollView viewWithTag:(currentPage+1)*10];
    
    NSDictionary *object = [NSDictionary dictionaryWithDictionary:[self.arrayData objectAtIndex:currentPage]];
    NSString *url=[object valueForKey:@"saytext"];
    NSData *data = [NSData dataWithContentsOfFile:[[SDImageCache sharedImageCache] cachePathForKey:[self getBigPicUrl:url]]];
    
    if(data.length<4)
    {
        
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
        animation.fromValue = [NSNumber numberWithFloat:0.0f];
        animation.toValue = [NSNumber numberWithFloat:1.0f];
        animation.duration = 0.5f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
        [gifImageView.layer addAnimation: animation forKey: @"FadeIn"];
    }
    
    [gifImageView setNeedsDisplay];
    gifImageView.isReady = YES;
    
    gifImageView.frame = CGRectMake(currentPage*320, 0, 320, __MainScreen_Height-44);
    gifImageView.contentSize = CGSizeMake(320, __MainScreen_Height-44);
    gifImageView.imageView.frame = CGRectMake(0, 0, gifImageView.imageView.image.size.width, gifImageView.imageView.image.size.height);
 
    if(gifImageView.imageView.frame.size.width>(__MainScreen_Width-10))
    {
        gifImageView.imageView.frame = CGRectMake(0, 0, __MainScreen_Width-10, ((__MainScreen_Width-10)/gifImageView.imageView.frame.size.width)*gifImageView.imageView.frame.size.height);
    }

    if(gifImageView.imageView.frame.size.height>(__MainScreen_Height-44))
    {
        gifImageView.imageView.frame = CGRectMake(0, 0, ((__MainScreen_Height-44)/gifImageView.imageView.frame.size.height)*gifImageView.imageView.frame.size.width, __MainScreen_Height-44);
    }
//让妖哥直接给你长方形的图，用ps切  有横着有熟的 他估计都传上去了可以切我教你
    gifImageView.imageView.center = CGPointMake(160, (float)(__MainScreen_Height-44)/2);
}

-(NSString *)getBigPicUrl:(NSString *)url
{
    NSString *suffix = nil;
    
    NSRange range = [url rangeOfString:@"." options:NSBackwardsSearch];
    
    if(range.location!=NSNotFound)
    {
        suffix = [url substringFromIndex:range.location];
        url = [url stringByAppendingString:suffix];
    }
    return url;
}

@end
